package com.sunshine.lnuplus.view

import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.sunshine.lnuplus.R

class DialogWithView : DialogFragment() {

    companion object{
        private lateinit var customView: View
        private var positive: DialogInterface.OnClickListener? = null
        private var negative: DialogInterface.OnClickListener? = null
        @JvmStatic
        fun newInstance(
            view: View,
            title: String,
            cancelable: Boolean,
            positive: DialogInterface.OnClickListener?,
            negative: DialogInterface.OnClickListener?) : DialogWithView{
            this.customView= view
            this.positive = positive
            this.negative = negative
            val bundle = Bundle()
            bundle.apply {
                putString("title", title)
                putBoolean("cancelable",cancelable)
            }
            val dialogWithView = DialogWithView()
            dialogWithView.arguments = bundle
            return dialogWithView
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        //必须removeAllViews否则有问题
        if(customView.parent != null){
            (customView.parent as ViewGroup).removeAllViews()
        }
        val builder = MaterialAlertDialogBuilder(context).apply {
            setTitle(arguments?.getString("title"))
            setView(customView)
            if(positive != null){
                setPositiveButton("保存", positive)
                setNegativeButton("取消", negative)
            }
        }
        return builder.create().apply {
            this@DialogWithView.isCancelable = arguments?.getBoolean("cancelable")!!
            if(context.getSharedPreferences("com.sunshine.lnuplus_preferences", Context.MODE_PRIVATE).getBoolean("night", false)){
                window?.setBackgroundDrawableResource(R.drawable.dialog_corner)
            }else{
                window?.setBackgroundDrawableResource(R.drawable.dialog_corner)
            }
        }
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.setLayout(
            (activity!!.windowManager.defaultDisplay.width * 0.75).toInt(),
            WindowManager.LayoutParams.WRAP_CONTENT
        )
    }

}